<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/9/6
 * Time: 13:59
 */
namespace app\admin\controller;

use app\index\service\ExtendService;
use app\middleware\AdminCheck;
use OSS\OssClient;
use think\facade\Db;

class SkillQuestion {

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [''] ]
    ];



    /**
     *   @SWG\Post(
     *     path="/admin/skillQuestion/add",
     *     tags={"后台考试技巧相关"},
     *     summary="添加技巧题目",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="skill_chapter_id,qid，title_，content_，skill_desc",
     *      type="string",
     *      description="skill_chapter_id（章节的id）,qid（题目的id），title_（标题），content_（描述），skill_desc（技巧描述）"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * @return \think\response\Json
     * @throws \OSS\Core\OssException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(){
        validateParam('skill_chapter_id,qid,title_,content_','skill_chapter_id,qid,title_,content_');
        //获取技巧章节
        $skill_chapter = Db::name('skill_chapter')
            ->where('id_',input('skill_chapter_id'))
            ->find();
        $qid = input('qid');//获取题目id的数组
        foreach ($qid as $k=>$v) {
            $data['city_'] = $skill_chapter['city_'];
            $data['skill_paper_id'] = $skill_chapter['skill_paper_id'];
            $data['skill_chapter_id'] = input('skill_chapter_id');
            $data['skill_chapter_id'] = input('skill_chapter_id');
            $data['qid'] = $v;
            $data['title_'] = input('title_');
            $data['content_'] = input('content_');
            $data['skill_desc'] = input('skill_desc');

            $service = new ExtendService();
            $token = cache('voiceToken');
            if (empty($token)) {
                $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret']);
                $token = $token_object['Token']['Id'];
                cache('voiceToken', $token, 1 * 60);
            }
            $text = "{$data['content_']}，{$data['skill_desc']}。";
            $text = urlencode($text);
            $appkey = config('system.ali')['aliVoiceKey'];
            $url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
            $stream_data = http_get($url);
            $url = app()->getRootPath() . '/public/voice/' . createNo() . '.mp3';
            file_put_contents($url, $stream_data, true); // 保存文件
            $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
            $bucket = config('system.ali')['bucket'];
            $object = 'voice/' . createNo() . '.mp3';
            $filePath = $url;
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            $voice_file = $result['info']['url'];
            $voice_file = str_replace('http', 'https', $voice_file);
            $data['voice_file'] = $voice_file;//语音文件
            Db::name('skill_chapter_question')->insert($data);
        }
        return success('添加成功');
    }




    /**
     *   @SWG\Post(
     *     path="/admin/skillQuestion/getList",
     *     tags={"后台考试技巧相关"},
     *     summary="技巧题目列表",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="pageNo,pageSize",
     *      type="string",
     *      description="pageNo(第几页),pageSize（一页多少条数据）,city_（城市）,skill_paper_id(技巧等级id),skill_chapter_id"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 章节列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('city_,pageNo,pageSize','city_,pageNo,pageSize');
        $param=input();
        $where[]=['a.city_','=',$param['city_']];
        if(!empty($param['skill_paper_id'])){
            $where[]=['a.skill_paper_id','=',$param['skill_paper_id']];
        }
        if(!empty($param['skill_chapter_id'])){
            $where[]=['a.skill_chapter_id','=',$param['skill_chapter_id']];
        }
        //获取总数
        $total=Db::name('skill_chapter_question')
            ->alias('a')
            ->field('a.*,b.question_,b.type_')
            ->leftJoin('question b','a.qid=b.id_')
            ->where($where)
            ->count();
        $offset=makeOffset($param['pageNo'],$param['pageSize']);

        $list=Db::name('skill_chapter_question')
            ->alias('a')
            ->field('a.*,b.question_,b.type_')
            ->leftJoin('question b','a.qid=b.id_')
            ->where($where)
            ->limit($offset,$param['pageSize'])
            ->select();
        return success('技巧题目列表',['total'=>$total,'list'=>$list]);
    }



    /**
     *   @SWG\Post(
     *     path="/admin/skillQuestion/edit",
     *     tags={"后台考试技巧相关"},
     *     summary="编辑技巧题目",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=true,
     *      name="id_,skill_chapter_id,qid，title_，content_，skill_desc",
     *      type="string",
     *      description="id_,skill_chapter_id（章节的id）,qid（题目的id），title_（标题），content_（描述），skill_desc（技巧描述）"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 编辑技巧题目
     * @return \think\response\Json
     * @throws \OSS\Core\OssException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(){
        validateParam('id_,skill_chapter_id,qid,title_,content_','id_,skill_chapter_id,qid,title_,content_');
        //获取技巧章节
        $skill_chapter = Db::name('skill_chapter')
            ->where('id_',input('skill_chapter_id'))
            ->find();
        $data['city_']=$skill_chapter['city_'];
        $data['skill_paper_id'] = $skill_chapter['skill_paper_id'];
        $data['skill_chapter_id']=input('skill_chapter_id');
        $data['skill_chapter_id']=input('skill_chapter_id');
        $data['qid']=input('qid');
        $data['title_']=input('title_');
        $data['content_']=input('content_');
        $data['skill_desc']=input('skill_desc');
        $service = new ExtendService();
        $token = cache('voiceToken');
        if(empty($token)){
            $token_object = $service->getalyuntoken(config('system.ali')['accessKeyId'],config('system.ali')['accessKeySecret']);
            $token = $token_object['Token']['Id'];
            cache('voiceToken',$token,1*60);
        }
        $text = "{$data['content_']}，{$data['skill_desc']}。";
        $text = urlencode($text);
        $appkey=config('system.ali')['aliVoiceKey'];
        $url="https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?appkey={$appkey}&token={$token}&text={$text}&format=mp3&voice=aijia";
        $stream_data = http_get($url);
        $url = app()->getRootPath().'/public/voice/'.createNo().'.mp3';
        file_put_contents($url, $stream_data, true); // 保存文件
        $ossClient = new OssClient(config('system.ali')['accessKeyId'], config('system.ali')['accessKeySecret'], config('system.ali')['endpoint']);
        $bucket = config('system.ali')['bucket'];
        $object = 'voice/'.createNo().'.mp3';
        $filePath = $url;
        $result = $ossClient->uploadFile($bucket, $object, $filePath);
        $voice_file = $result['info']['url'];
        $voice_file = str_replace('http','https',$voice_file);
        $data['voice_file'] = $voice_file;//语音文件
        Db::name('skill_chapter_question')
            ->where('id_',input('id_'))
            ->update($data);
        return success('编辑成功');
    }




    /**
     *   @SWG\Post(
     *     path="/admin/skillQuestion/delete",
     *     tags={"后台考试技巧相关"},
     *     summary="删除技巧题目",
     *     consumes={"application/json"},
     *     produces={"application/json"},
     *     @SWG\Parameter(
     *      in="query",
     *      required=false,
     *      name="ids",
     *      type="string",
     *      description="ids"),
     *     @SWG\Response(response="200",description="ok")
     *  )
     */
    /**
     * 删除题目
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete(){
        validateParam('ids','ids');
        Db::name('skill_chapter_question')
            ->where('id_','in',input('ids'))
            ->delete();
        return success('删除成功');
    }



}